#ifndef COMM_HPP
#define COMM_HPP

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <cassert>

#define mode 0666
#define Path "./pipe"

using namespace std;

class Pipe
{
public:
    Pipe(const string & path=Path)
    :_path(path)
    {
        umask(0);
        int n=mkfifo(_path.c_str(),mode);
        if(n==0)
        {
            cout<<"mkfifo succuss"<<endl;
        }
        else
        {
            cerr<<"mkfifo failed error:"<<errno<<",errorstring"<<strerror(errno)<<endl;
        }
    }

    ~Pipe()
    {   
        const char*pipename="fifo";
        int n=unlink(pipename);
        if(n==0)
        {
            cout<<"remove pipe succuss,pipe path:"<<_path<<endl;
        }
        else
        {
            cerr<<"remove pipe error errno code:"<<errno<<"strerror:"<<strerror(errno)<<endl;
        }
    }
private:
    string _path;
};

class Sync
{
public:
    Sync() : rfd(-1), wfd(-1)
    {
    }
    void OpenReadOrDie()
    {
        rfd = open(Path, O_RDONLY);
        if (rfd < 0)
            exit(1);
    }
    void OpenWriteOrDie()
    {
        wfd = open(Path, O_WRONLY);
        if (wfd < 0)
            exit(1);
    }
    bool Wait()//管道等待读取
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(rfd, &c, sizeof(uint32_t));
        if (n == sizeof(uint32_t))
        {
            std::cout << "server wakeup, begin read shm..." << std::endl;
        }
        else if (n == 0)
        {
            ret = false;
        }
        else
        {
            return false;
        }
        return ret;
    }
    void Wakeup()//向管道写入
    {
        uint32_t c = 0;
        ssize_t n = write(wfd, &c, sizeof(c));
        assert(n == sizeof(uint32_t));

        std::cout << "wakeup server..." << std::endl;
    }
    ~Sync() {}

private:
    int rfd;
    int wfd;
};

#endif